﻿using System.Threading;

public class GameMessageHeader
{
    private static int MESSAGE_SEQ_ID = 0;
    public const int HEADER_WRITE_LENGTH = 24;
    public int MessageSize { set; get; }
    public int MessageSeqId { get; set; }
    public int MessageId { get; set; }
    public long SendTime { get; set; }

    public EnumMessageType MessageType { get; set; }

    public int ErrorCode { get; set; }
    public int Version { get; set; }
    public bool IsCompress { get; set; }
    public bool IsEncrypt { get; set; }
    public int ServiceId { get; set; }

    public void Write(ByteBuf byteBuf)
    {
        MessageSeqId = Interlocked.Increment(ref MESSAGE_SEQ_ID);
        byteBuf.WriteInt(MessageSeqId);
        byteBuf.WriteInt(MessageId);
        
        SendTime = DateUtil.CurrentSecond();
        byteBuf.WriteLong(SendTime);
        byteBuf.WriteInt(Version);
        byteBuf.WriteShort(ServiceId);
        byteBuf.WriteByte(IsCompress ? 1 : 0);
        byteBuf.WriteByte(IsEncrypt ? 1 : 0);

    }

    public static int ReadMessageId(ByteBuf byteBuf)
    {
        byteBuf.MarkReaderIndex();
        byteBuf.SkipBytes(8);
        int messageId = byteBuf.ReadInt();
        byteBuf.ResetReaderIndex();
        return messageId;
    }

    public void Read(ByteBuf byteBuf)
    {
        this.MessageSize = byteBuf.ReadInt();
        this.MessageSeqId = byteBuf.ReadInt();
        this.MessageId = byteBuf.ReadInt();
        this.SendTime = byteBuf.ReadLong();
        this.Version = byteBuf.ReadInt();
        this.ErrorCode = byteBuf.ReadInt();
        byteBuf.SkipBytes(1);//跳过消息类型的读取
        this.IsEncrypt = byteBuf.ReadByte() == 1 ? true : false;
        this.IsCompress = byteBuf.ReadByte() == 1 ? true : false;
        
    }

}
